<?php
//
namespace app\home\controller;

use app\common\model\UserModel;
use Org\Util\HelpUtil;
use think\Request;

class PublicController extends BaseController
{

    private $userModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->userModel = new UserModel();
    }

    /*
     * 会员登录
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (!captcha_check($data['vcode'])) {
                $this->error('验证码错误');
            };
            $result = $this->validate($data, 'UserValidate.login');
            if (!$result) {
                $this->error($result);
            }
            $des = $this->userModel->checkMemberLogin($data['account'], $data['password']);
            if ($des===false) {
                $this->error($this->userModel->getError());
            }
            cookie('memberDes', $des);
            $data['url'] = empty($data['url']) ? url('home/Index/index') : $data['url'];
            $this->success('登录成功！', urldecode($data['url']));
        }
        return $this->fetch();
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        cookie('memberDes', null);
        $reUrl=$this->request->param('reurl','');
        $this->success('退出成功',empty($reUrl)?url('/home/Index/index'):$reUrl);
    }
    /*
    * 会员注册
    */
    public function reg()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            if (!isset($data['mobile'])) { //未设置mobile时才验证图形验证码
                $captcha = $data['vcode'];
                if (!captcha_check($captcha)) {
                    $this->error('验证码错误');
                };
            } else { //核实短信验证码
                $smsValid = session('sms_valid');
                if ($smsValid[1] < time() - 3 * 60) {
                    session('sms_valid', null);
                    $this->error('短信验证码已失效!');
                } else if ($smsValid[0] != $data['mcode']) {
                    $this->error('短信验证码错误');
                }
            }
            $result = $this->validate($data, 'UserValidate.reg');
            if (true !== $result) {
                $this->error($result);
            }
            $data['group_id'] = 3001;
            if ($this->userModel->addData($data)) {
                session('sms_valid', null);
                $this->success('注册成功！', url('/home/Public/login'));
            } else {
                $this->error($this->userModel->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 发送短信
     */
    public function sendSms()
    {
        $mobile = $this->request->param('mobile');
        $vcode = $this->request->param('vcode');
        if ($this->userModel->isMobile($mobile) === false) {
            $this->error('手机号格式有误！');
        }
        if (!captcha_check($vcode)) {
            $this->error('图形验证码错误！');
        };
        $isReg = $this->userModel->where('mobile', $mobile)->where('utype', 'member')->find();
        if ($isReg) {
            $this->error('该手机号已注册，请直接登录！');
        }
        $randNum = HelpUtil::randString(6, 1);
        $data = [$randNum, 3];
        send_sms($mobile, $data, '149180');
        session('sms_valid', [$randNum, time()]);
        $this->success('短信发送成功!');
    }

    /*
    * 找回密码
    */
    public function findPwd()
    {
        $step = $this->request->param('step', 1);
        if ($this->request->isAjax()) {
            switch ($step) {
                case 1:
                    $account = $this->request->param('account');
                    $vcode = $this->request->param('vcode');
                    if (!captcha_check($vcode)) {
                        $this->error('图形验证码错误！');
                    };
                    $field = $this->userModel->checkUserName($account);
                    if (in_array($field, ['mobile', 'email'])) {
                        $isReg = $this->userModel->where($field, $account)->where('utype', 'member')->find();
                        if (!$isReg) {
                            $this->error('该帐户未注册！');
                        } else {
                            $randNum = HelpUtil::randString(6, 1);
                            if ($field == 'mobile') {
                                $data = [$randNum, 3];
                                send_sms($account, $data, '149180');
                            }
                            if ($field == 'email') {
                                send_mail($account, '会员密码找回', '使用重置验证码来重置您的密码:' . $randNum);
                            }
                            session('sms_valid', [$randNum, time()]);
                            session('find_uid', $isReg['uid']);
                            $this->success('success', url('home/Public/findPwd', ['step' => 2]));
                        }
                    } else {
                        $this->error('请输入有效的手机号或邮箱！');
                    }
                    break;
                case 2:
                    $mcode = $this->request->param('mcode');
                    $smsValid = session('sms_valid');
                    if ($smsValid[1] < time() - 3 * 60) {
                        session('sms_valid', null);
                        $this->error('验证码已失效!');
                    } else if ($smsValid[0] != $mcode) {
                        $this->error('验证码错误');
                    }
                    $this->success('success', url('home/Public/findPwd', ['step' => 3]));
                    break;
                case 3:
                    $password = $this->request->param('password');
                    $passwordConfirm = $this->request->param('password_confirm');
                    if (empty($password)) {
                        $this->error('密码不能为空！');
                    }
                    if ($password == $passwordConfirm) {
                        $uid = session('find_uid');
                        if ($uid) {
                            $this->userModel->where('uid', $uid)->setField('password', md5($password));
                            session('find_uid', null);
                            $this->success('success', url('home/Public/findPwd', ['step' => 4]));
                        } else {
                            $this->error('参数错误！');
                        }
                    } else {
                        $this->error('新密码和确认密码不一致！');
                    }
                    break;
                default:
                    $this->error('参数错误！');
                    break;
            }
        }
        $this->assign('step', $step);
        return $this->fetch();
    }


    /**
     * 微信公众号验证函数
     */
    public function verifyWechat()
    {
        $deptId = $this->request->param('dept_id/d');
        $deptInfo = new BusDeptModel();
        $deptInfo = $deptInfo->get($deptId);
        $wechat = &load_wechat('Receive',$deptInfo['wx_config']);
        /* 验证接口 */
        if ($wechat->valid() === FALSE) {
            // 接口验证错误，记录错误日志
            // log_message('ERROR', "微信被动接口验证失败，{$wechat->errMsg}[{$wechat->errCode}]");
            // 退出程序
            exit($wechat->errMsg);
        }
    }


}
